package com.shadow.bus.main.complete;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.shadow.bus.config.ItemFiled;
import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.entity.ConfirmEntity;
import com.shadow.bus.entity.PersonEntity;
import com.shadow.bus.entity.PostRepairInfo;
import com.shadow.bus.entity.RepairEntity;
import com.shadow.bus.entity.TroubleEntity;
import com.shadow.bus.entity.TroubleOperationEntity;
import com.shadow.bus.event.PopChildEvent;
import com.shadow.bus.event.RefreshMainEvent;
import com.shadow.bus.event.RefreshWorkEvent;
import com.shadow.bus.event.SearchPersonEvent;
import com.shadow.bus.ic.IcManager;
import com.shadow.bus.ic.OpenIcEvent;
import com.shadow.bus.main.search_code.NameFragment;
import com.shadow.bus.tools.AESUtils;
import com.shadow.bus.tools.SPUtils;
import com.shadow.bus.tools.UsbUtil;
import com.tepth.shadow.ui.dialog.sweet.DialogDelegate;
import com.tepth.shadow.ui.dialog.sweet.SweetAlertDialogDelegate;
import com.tepth.shadow.ui.recycler.BaseDecoration;
import com.tepth.shadow.ui.recycler.MultipleItemEntity;
import com.tepth.shadow.ui.recycler.RecyclerViewNoBugLinearLayoutManager;
import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;
import com.zhangyu.shadow.core.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import busfix.tepth.com.shadow_bus.R;
import busfix.tepth.com.shadow_bus.R2;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zhangyu
 * @date 2018/7/4
 */

public class CompleteWorkDelegate extends RxShadowDelegate {
    private static final String BUS_CODE = "busCode";
    private static final String BUS_ID = "busId";


    public static CompleteWorkDelegate newInstance(String code, long id) {
        Bundle args = new Bundle();
        args.putString(BUS_CODE, code);
        args.putLong(BUS_ID, id);
        CompleteWorkDelegate fragment = new CompleteWorkDelegate();
        fragment.setArguments(args);
        return fragment;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    private String mBusCode;
    private long mBusId;
    private DialogDelegate mDialogDelegate;
    private CompleteAdapter mCompleteAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBusCode = bundle.getString(BUS_CODE);
            mBusId = bundle.getLong(BUS_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_complete_work;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        mToolbar.setTitle("车辆编号:" + mBusCode + "竣检信息");
        LinearLayoutManager layoutManager = new RecyclerViewNoBugLinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources()
                .getColor(R.color.color_white), 2));
        mCompleteAdapter = new CompleteAdapter(null);
        mRecyclerView.setAdapter(mCompleteAdapter);
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (R.id.btn_rework == view.getId()) {
                    MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                    if (entity != null) {
                        makeReworkData((TroubleEntity) entity.getField(ItemFiled.ITEM_OBJ));
                    }
                }
            }
        });
        mDialogDelegate = new SweetAlertDialogDelegate(getContext());
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        EventBus.getDefault().register(this);
        requestData();
    }

    private void requestData() {
        mDialogDelegate.showProgressDialog(false, "正在加载...");
        mDisposables.add(RxRestClient.builder()
                .url(ServiceUrl.REPAIR_INFO)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("id", mBusId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        new CompleteDataConverter().convert(response, new CompleteDataConverter.OnConverterListener() {
                            @Override
                            public void onConverterAllData(ArrayList<MultipleItemEntity> list) {
                                try {
                                    mCompleteAdapter.setNewData(list);
                                    mDialogDelegate.clearDialog();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void canCompletePunch(boolean isComplete) {
                                try {
                                    if (!isComplete) {
                                        mDialogDelegate.stopProgressWithFailed("无法竣检",
                                                "您还有未处理的故障!", new DialogDelegate.OnDialogListener() {
                                                    @Override
                                                    public void onClick() {
                                                        mDialogDelegate.clearDialog();
                                                        pop();
                                                    }
                                                });
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build()
                .get());
    }

    private void makeReworkData(TroubleEntity troubleEntity) {
        PostRepairInfo postRepairInfo = new PostRepairInfo();
        postRepairInfo.setId(mBusId);
        List<PostRepairInfo.ListTroubleBean> troubleBeans = new ArrayList<>();
        postRepairInfo.setListTrouble(troubleBeans);
        PostRepairInfo.ListTroubleBean troubleBean = new PostRepairInfo.ListTroubleBean();
        troubleBean.setName(troubleEntity.getName());
        troubleBean.setId(troubleEntity.getId());
        ArrayList<TroubleOperationEntity> operationEntities = troubleEntity.getListContent();
        if (operationEntities != null) {
            for (TroubleOperationEntity entity : operationEntities) {
                entity.setIsRework(true);
            }
        }
        troubleBean.setListContent(operationEntities);
        troubleBeans.add(troubleBean);
        //is开头的属性
        Gson gson = new Gson();
        String info = gson.toJson(postRepairInfo);
        //String info = JSON.toJSONString(postRepairInfo);
        Log.e("workCard", info);
        mDialogDelegate.showProgressDialog(true, "正在提交...");
        mDisposables.add(RxRestClient.builder()
                .url(ServiceUrl.REWORK)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("repairInfo", info)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mDialogDelegate.stopProgressWithSuccess("返工成功", "请重新处理该故障项!",
                                new DialogDelegate.OnDialogListener() {
                                    @Override
                                    public void onClick() {
                                        mDialogDelegate.clearDialog();
                                        EventBus.getDefault().post(new RefreshWorkEvent());
                                        pop();
                                    }
                                });
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogDelegate.stopProgressWithFailed("提交失败", msg);
                    }
                })
                .build()
                .post());
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    public static final int MIN_CLICK_DELAY_TIME = 1000;
    private long mLastClickTime = 0;

    @OnClick(R2.id.btn_complete_work)
    public void onCompletePunch() {
        //防止多次点击
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - mLastClickTime > MIN_CLICK_DELAY_TIME) {
            mLastClickTime = currentTime;
            if (ShadowPreference.getAppFlag(SpKey.KEY_CARD_WAY)) {
                if (UsbUtil.hasUsbDevice(getActivity())) {
                    IcManager.getInstance().openDevice();
                    mDialogDelegate.showProgressDialog(true, "正在打开设备...");
                    mDialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            IcManager.getInstance().leisureDevice();
                        }
                    });
                } else {
                    ToastUtils.showToast(getContext(), "未检测到打卡器");
                }
            } else {
                NameFragment.newInstance().show(getChildFragmentManager(), "fragment_name");
            }
        } else {
            ToastUtils.showToast(getActivity(), "点得太快啦!");
        }
    }

    @Subscribe(priority = 1)
    public void onICEvent(final OpenIcEvent event) {
        //接收了该事件就拦截掉 不会继续往优先级小于priority的地方传递
        EventBus.getDefault().cancelEventDelivery(event);
        if (!event.isSuccess) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mDialogDelegate != null) {
                        mDialogDelegate.changeText(event.mTitle, (String) event.mObject);
                    }
                }
            });
        } else {
            byte[] displayContents = (byte[]) event.mObject;
            String[] result = analysisData(new String(displayContents));
            if (result != null) {
                //将打卡人存入缓存
                HashMap<String, String> hashMap = (HashMap<String, String>) SPUtils.getObject(getContext(), SpKey.KEY_HISTORY_USER);
                if (hashMap == null) {
                    hashMap = new HashMap<>();
                }
                hashMap.put(result[0], result[1]);
                SPUtils.putObject(getContext(), SpKey.KEY_HISTORY_USER, hashMap);
                punch(result);
            }
        }
    }

    @Subscribe(priority = 1)
    public void onSearchPersonEvent(SearchPersonEvent event) {
        EventBus.getDefault().cancelEventDelivery(event);
        String[] result = new String[2];
        result[0] = event.code;
        result[1] = event.name;
        punch(result);
    }

    private String[] analysisData(String data) {
        String result;
        try {
            result = AESUtils.code_desEncrypt(data);
            if (result.isEmpty()) {
                ToastUtils.showToast(getContext(), "AES解码失败");
                return null;
            }
            String[] results = result.split("_");
            if (result.length() < 2) {
                ToastUtils.showToast(getContext(), "数组长度小于2");
                return null;
            }
            return results;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void punch(String[] result) {
        String personNumber = result[0];
        RepairEntity mRepairInfo = new RepairEntity();
        mRepairInfo.setId(mBusId);
        List<ConfirmEntity> list = new ArrayList<>();
        ConfirmEntity listConfirmBean = new ConfirmEntity();

        listConfirmBean.setConfirmType(3);
        PersonEntity personEntity = new PersonEntity();
        personEntity.setCode(personNumber);
        listConfirmBean.setConfirmPerson(personEntity);
        list.add(listConfirmBean);
        mRepairInfo.setListConfirm(list);
        mRepairInfo.setListTrouble(new ArrayList<TroubleEntity>());
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mDialogDelegate != null) {
                    if (mDialogDelegate.getDialog().isShowing()) {
                        mDialogDelegate.changeText("读取成功!", "正在提交...");
                    } else {
                        mDialogDelegate.showProgressDialog(true, "正在提交...");
                    }
                }
            }
        });
        Gson gson = new Gson();
        String info = gson.toJson(mRepairInfo);
        // String info = JSON.toJSONString(mRepairInfo);
        mDisposables.add(RxRestClient.builder()
                .url(ServiceUrl.START_REPAIR)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("repairInfo", info)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mDialogDelegate.stopProgressWithSuccess("提交成功", "竣检成功!",
                                new DialogDelegate.OnDialogListener() {
                                    @Override
                                    public void onClick() {
                                        mDialogDelegate.clearDialog();
                                        EventBus.getDefault().post(new RefreshMainEvent());
                                        EventBus.getDefault().post(new PopChildEvent());
                                    }
                                });
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogDelegate.stopProgressWithFailed("提交失败", msg);
                    }
                })
                .build()
                .post());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null && data.hasExtra("BarCodeContents")) {
            byte[] displayContents = data.getByteArrayExtra("BarCodeContents");
            String[] result = analysisData(new String(displayContents));
            if (result != null) {
                punch(result);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
